from sqlalchemy.orm import Session
from schema import Plot_schema
from model import Plot_model



def get_Plot(db: Session, ID: int):
    return db.query(Plot_model.Plot).filter(Plot_model.Plot.ID == ID).first()


def get_all_Plot(db: Session):
    return db.query(Plot_model.Plot).all()


def delete_Plot(db: Session, ID):
    to_delete = db.query(Plot_model.Plot).filter(Plot_model.Plot.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Plot(db: Session, Plot: Plot_schema.Plot):
    db_Plot = Plot_model.Plot(
        Name=Plot.Name,
        Area=Plot.Area,
        Crop=Plot.Crop,
        PlantingDate=Plot.PlantingDate,
        GrowthStage=Plot.GrowthStage,
        FarmID=Plot.FarmID,
        LesseeID=Plot.LesseeID,
    )
    db.add(db_Plot)
    db.commit()
    db.refresh(db_Plot)
    return db_Plot


def update_Plot(db: Session, ID, field_name, new_value):
    db_Plot = db.query(Plot_model.Plot).filter(Plot_model.Plot.ID == ID).first()
    setattr(db_Plot, field_name, new_value)
    db.commit()
    db.refresh(db_Plot)
    return db_Plot
